﻿using System;
using System.Collections.Generic;
using System.Text;
using Tauren.Business.DLL.Base;
using Tauren.Business.DLL.Resouces;
using Tauren.Business.Entity.Config;
using Tauren.Business.Entity.Const;
using Tauren.Business.Entity.Enum;
using Tauren.Business.Entity.Global;
using Tauren.Business.Entity.Input;
using Tauren.Business.Entity.Model;
using Tauren.Business.Infrastructure.Globals;
using System.Linq;
using System.Transactions;
using Tauren.Business.Entity.Output;
using Tauren.Business.DLL.ParametersDLL;

namespace Tauren.Business.Service.ParameterBLL
{
    /// <summary>
    /// 字典
    /// </summary>
    public class ParameterService : Base.BaseService, IParameterService
    {
        private IParametersBusiness business;
        public ParameterService(IParametersBusiness _business, IConnectionBLLBase connectionBLL, IMenuResourcesBusiness resourcesBusiness) : base(_business, connectionBLL, resourcesBusiness)
        {
            this.business = _business;
            this.ResourcesInfo = this.GetResources(GlobalConst.RESOURCES_FLAG_MODULE_PARAMETER_KEY);
            this.JudePrmission(GlobalConst.RESOURCES_FLAG_MODULE_PARAMETER_KEY.ToLower());
        }

        public IResponseMessage Add(Parameters_InPut data)
        {
            if (!HavePermission) return ErrorType.BUSINESS_WITHOUT_PERMISSION.Failure(this.CommonText(ErrorType.BUSINESS_WITHOUT_PERMISSION));
            if (data is null) return GlobalErrorType.GLOBAL_NOT_FOUND_INPUT_DATA.Failure(this.CommonText(GlobalErrorType.GLOBAL_NOT_FOUND_INPUT_DATA));
            var codes = business.IsPermissionCodeRepeat(0, data.Code);
            if (codes) return GlobalErrorType.GLOBAL_REPEAT_CODE.Failure(this.CommonText(GlobalErrorType.GLOBAL_REPEAT_CODE));
            Parameters Parameter;
            ToModel(data, out Parameter);
            Parameter.Enable = true;
            Parameter.HaveDelete = false;
            Parameter.Sequence = business.GetSeq();
            Parameter.Creator = this.Global.EmpId;
            Parameter.Modifier = this.Global.EmpId;
            Parameter.Creatdate = DateTime.Now;
            Parameter.Modifdate = DateTime.Now;
            using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions() { IsolationLevel = IsolationLevel.ReadCommitted }))
            {
                bool b = false;
                long id = business.Add(Parameter);
                if (id > 0)
                {
                    List<ParameterValue> values;
                    ToModel(data.Values, out values);
                    if (values == null) values = new List<ParameterValue>();
                    values.ForEach(o => o.MainCode = Parameter.Code);
                    b = business.AddParameterValue(Parameter.Code, values);
                }
                if (b)
                {
                    ts.Complete();
                    return "".OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_SAVE_SUCCESSINFO.ToString()));
                }
                else return GlobalErrorType.GLOBAL_SAVE_FAILURE.OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_SAVE_FAILURE));
            }
        }

        public IResponseMessage Config(string PageType)
        {
            if (!HavePermission) return ErrorType.BUSINESS_WITHOUT_PERMISSION.Failure(this.CommonText(ErrorType.BUSINESS_WITHOUT_PERMISSION));
            List<OutPutConfig> Fields = new List<OutPutConfig>();

            OutPutConfig config = new OutPutConfig();
            config.Label = this.CommonText("thcode");
            config.FieldKey = "code";
            config.MenuCode = GlobalConst.RESOURCES_FLAG_MODULE_PARAMETER_KEY.ToLower();
            config.ControlType = ControlType.text;
            config.Show = true;
            config.Editor = PageType != "view" && PageType != "edit";
            config.Required = PageType != "view" && PageType != "edit";
            Dictionary<object, object> rule = new Dictionary<object, object>();
            if (PageType != "view")
            {
                #region 添加验证规则

                rule.Add("required", true);
                rule.Add("message", this.Resources("coderequired"));
                rule.Add("trigger", "blur");
                config.Rules.Add(rule);
                ///长度
                rule = new Dictionary<object, object>();
                rule.Add("min", 1);
                rule.Add("max", 30);
                rule.Add("message", this.Resources("codemax"));
                rule.Add("trigger", "blur");
                config.Rules.Add(rule);
                ///正则
                rule = new Dictionary<object, object>();
                rule.Add("pattern", "^([a-zA-Z0-9]){1,30}$");
                rule.Add("message", this.Resources("codedregx"));
                rule.Add("trigger", "blur");
                config.Rules.Add(rule);
            }
            Fields.Add(config);
            #endregion

            #region 中文名
            config = new OutPutConfig();
            config.Label = this.CommonText("thcnname");
            config.FieldKey = "cnName";
            config.MenuCode = GlobalConst.RESOURCES_FLAG_MODULE_PARAMETER_KEY.ToLower();
            config.ControlType = ControlType.textarea;
            config.Show = true;
            config.Editor = PageType != "view";
            config.Required = PageType != "view";
            rule = new Dictionary<object, object>();
            if (PageType != "view")
            {
                rule.Add("required", true);
                rule.Add("message", this.CommonText("fieldsrequired"));
                rule.Add("trigger", "blur");
                config.Rules.Add(rule);
                ///长度
                rule = new Dictionary<object, object>();
                rule.Add("min", 1);
                rule.Add("max", 100);
                rule.Add("message", this.Resources("cnnamemax"));
                rule.Add("trigger", "blur");
                config.Rules.Add(rule);
            }
            Fields.Add(config);
            #endregion
            #region 英文名
            config = new OutPutConfig();
            config.Label = this.CommonText("thenname");
            config.FieldKey = "enName";
            config.MenuCode = GlobalConst.RESOURCES_FLAG_MODULE_PARAMETER_KEY.ToLower();
            config.ControlType = ControlType.textarea;
            config.Show = true;
            config.Editor = PageType != "view";
            config.Required = PageType != "view";
            rule = new Dictionary<object, object>();
            if (PageType != "view")
            {
                rule.Add("required", true);
                rule.Add("message", this.CommonText("fieldsrequired"));
                rule.Add("trigger", "blur");
                config.Rules.Add(rule);
                ///长度
                rule = new Dictionary<object, object>();
                rule.Add("min", 1);
                rule.Add("max", 200);
                rule.Add("message", this.Resources("ennamemax"));
                rule.Add("trigger", "blur");
                config.Rules.Add(rule);
            }
            Fields.Add(config);
            #endregion      

            config = new OutPutConfig();
            config.FieldKey = "values";
            config.MenuCode = GlobalConst.RESOURCES_FLAG_MODULE_ROLE_KEY.ToLower();
            config.ControlType = ControlType.records;
            config.Label = this.Resources("parametervalue");
            config.Show = true;
            config.Editor = PageType != "view";
            BuliedTableResConfig(config.Tables, PageType);
            Fields.Add(config);
            return Fields.Succeed();
        }

        public IResponseMessage Delete(long AutoID)
        {
            if (!HavePermission) return ErrorType.BUSINESS_WITHOUT_PERMISSION.Failure(this.CommonText(ErrorType.BUSINESS_WITHOUT_PERMISSION));
            var data = business.Get<Parameters>(AutoID);
            if (data is null) return GlobalErrorType.GLOBAL_NOT_FOUND_DB_DATA.Failure(this.CommonText(GlobalErrorType.GLOBAL_NOT_FOUND_DB_DATA));
            data.Enable = false;
            data.HaveDelete = true;
            data.Modifier = Global.EmpId;
            data.Modifdate = DateTime.Now;
            bool b = business.Update<Parameters>(data);
            if (b)
            {
                return "".OnSucceed(this.Resources(GlobalErrorType.GLOBAL_DELETE_SUCCESSINFO));
            }
            else return GlobalErrorType.GLOBAL_DELETE_FAILURE.OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_DELETE_FAILURE));
        }

        public IResponseMessage Edit(Parameters_InPut data)
        {
            if (!HavePermission) return ErrorType.BUSINESS_WITHOUT_PERMISSION.Failure(this.CommonText(ErrorType.BUSINESS_WITHOUT_PERMISSION));
            if (data is null) return GlobalErrorType.GLOBAL_NOT_FOUND_INPUT_DATA.Failure(this.CommonText(GlobalErrorType.GLOBAL_NOT_FOUND_INPUT_DATA));
            var singe = business.Get<Parameters>(data.AutoId);
            if (singe is null) return GlobalErrorType.GLOBAL_NOT_FOUND_DB_DATA.Failure(this.CommonText(GlobalErrorType.GLOBAL_NOT_FOUND_DB_DATA));
            var codes = business.IsPermissionCodeRepeat(data.AutoId, data.Code);
            if (codes) return GlobalErrorType.GLOBAL_REPEAT_CODE.Failure(this.CommonText(GlobalErrorType.GLOBAL_REPEAT_CODE));
            Parameters tb;
            ToModel(data, out tb);
            tb.Sequence = singe.Sequence;
            tb.Enable = singe.Enable;
            tb.HaveDelete = singe.HaveDelete;
            tb.Creatdate = singe.Creatdate;
            tb.Creator = singe.Creator;
            tb.Modifier = this.Global.EmpId;
            tb.Modifdate = DateTime.Now;
            using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions() { IsolationLevel = IsolationLevel.ReadCommitted }))
            {
                bool b = business.Update(tb);
                if (b)
                {
                    List<ParameterValue> values;
                    ToModel(data.Values, out values);
                    if (values == null) values = new List<ParameterValue>();
                    values.ForEach(o => o.MainCode = data.Code);
                    b = business.AddParameterValue(data.Code, values);
                }
                if (b)
                {
                    ts.Complete();
                    return "".OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_SAVE_SUCCESSINFO.ToString()));
                }
                else return GlobalErrorType.GLOBAL_SAVE_FAILURE.OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_SAVE_FAILURE));
            }
        }

        public IResponseMessage Enable(long AutoID)
        {
            if (!HavePermission) return ErrorType.BUSINESS_WITHOUT_PERMISSION.Failure(this.CommonText(ErrorType.BUSINESS_WITHOUT_PERMISSION));
            var data = business.Get<Parameters>(AutoID);
            if (data is null) return GlobalErrorType.GLOBAL_NOT_FOUND_DB_DATA.Failure(this.CommonText(GlobalErrorType.GLOBAL_NOT_FOUND_DB_DATA));
            data.Enable = !data.Enable;
            data.Modifier = Global.EmpId;
            data.Modifdate = DateTime.Now;
            bool b = business.Update<Parameters>(data);
            if (b)
            {
                return "".OnSucceed(this.CommonText(data.Enable.Value ? GlobalErrorType.GLOBAL_ENABLE_SUCCESSINFO : GlobalErrorType.GLOBAL_DISABLE_SUCCESSINFO));
            }
            else return data.Enable.Value ? GlobalErrorType.GLOBAL_ENABLE_FAILURE.OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_ENABLE_FAILURE)) : GlobalErrorType.GLOBAL_DISABLE_FAILURE.OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_DISABLE_FAILURE));
        }

        public IResponseMessage Get(long AutoID)
        {
            if (!HavePermission) return ErrorType.BUSINESS_WITHOUT_PERMISSION.Failure(this.CommonText(ErrorType.BUSINESS_WITHOUT_PERMISSION));
            Parameters Parameter = business.Get<Parameters>(AutoID);
            Parameters_OutPut _OutPut = new Parameters_OutPut();
            if (Parameter != null)
            {
                ToViewModel(Parameter, out _OutPut);
                if (_OutPut != null)
                {
                    var tables = business.GetParametersByCode(_OutPut.Code);
                    List<ParameterValue_OutPut> puts;
                    ToViewModel(tables, out puts);
                    _OutPut.Values = !puts.Any() ? new List<ParameterValue_OutPut>() : puts;
                }
            }
            return _OutPut.Succeed();
        }

        public IResponseMessage Pages(QueryModel queryModel)
        {
            if (!HavePermission) return ErrorType.BUSINESS_WITHOUT_PERMISSION.Failure(this.CommonText(ErrorType.BUSINESS_WITHOUT_PERMISSION));
            TableListModel<PageParametersTable> tableListModel = new TableListModel<PageParametersTable>();
            List<TableListHeaderModele> Headers = new List<TableListHeaderModele>();
            Headers.Add(new TableListHeaderModele() { Key = "rowNo", Name = CommonText("rowNo"), Width = 50, Align = "center", Fixed = true });
            Headers.Add(new TableListHeaderModele() { Key = "autoId", Name = CommonText("autoid"), Width = 70, Hide = true, Type = "primary_key", Align = "center", SorTable = SortType.custom.ToString(), Fixed = true });
            Headers.Add(new TableListHeaderModele() { Key = "code", Name = CommonText("thcode"), Width = 160, Align = "left", SorTable = SortType.custom.ToString(), Fixed = true, Filter = true });
            Headers.Add(new TableListHeaderModele() { Key = "cnName", Name = CommonText("thcnname"), Width = 260, Align = "left", IsOperation = true, SorTable = SortType.custom.ToString(), Fixed = true, Filter = true });
            Headers.Add(new TableListHeaderModele() { Key = "enName", Name = CommonText("thenname"), Width = 220, Align = "left", SorTable = SortType.custom.ToString(), Fixed = true, Filter = true });
            Headers.Add(new TableListHeaderModele() { Key = "dic_Enable", Name = CommonText("thstate"), IsTag = true, Width = 100, Align = "center", SorTable = SortType.custom.ToString() });
            Headers.Add(new TableListHeaderModele() { Key = "dic_Creator", Name = CommonText("diccreator"), Width = 120, Align = "center" });
            Headers.Add(new TableListHeaderModele() { Key = "dic_Creatdate", Name = CommonText("diccreatdate"), Width = 160, Align = "center" });
            Headers.Add(new TableListHeaderModele() { Key = "action", Name = "操作", Width = 160, Align = "center" });
            long Total = 0;
            List<PageParametersTable> Data = business.Pages(queryModel, out Total);
            if (Data.Any())
            {
                Data.ForEach(o =>
                {

                    o.Dic_Enable = CommonText(o.Enable ? GlobalConst.RESOURCES_CONTENT_ENABLE_KEY : GlobalConst.RESOURCES_CONTENT_DISABLE_KEY);
                    o.Dic_Creator = EmpDictionary.ContainsKey(o.Creator) ? EmpDictionary[o.Creator] : "";
                    o.Dic_Creatdate = o.Creatdate.Value.ToString(GlobalConst.DATE_FORMAT_SECONDS);
                    o.Row_Style = o.Enable ? "" : "danger";
                    o.Operations = new List<SystemButton>();
                    if (Global.IsAdmin && (Buttons is null || !Buttons.Any()))
                    {
                        BuliderButtons(o.Operations, o.Code, o.AutoId, ButtomType.edit);
                        BuliderButtons(o.Operations, o.Code, o.AutoId, ButtomType.detaile);
                        BuliderButtons(o.Operations, o.Code, o.AutoId, !o.Enable ? ButtomType.enable : ButtomType.disable);
                        BuliderButtons(o.Operations, o.Code, o.AutoId, ButtomType.delete);
                    }
                    else
                    {
                        if (Buttons.Any(o => o.Location == ButtomLocation.center.ToString() && o.Value == ButtomType.edit.ToString()))
                            BuliderButtons(o.Operations, o.Code, o.AutoId, ButtomType.edit);
                        if (Buttons.Any(o => o.Location == ButtomLocation.center.ToString() && o.Value == ButtomType.detaile.ToString()))
                            BuliderButtons(o.Operations, o.Code, o.AutoId, ButtomType.detaile);
                        if (Buttons.Any(o => o.Location == ButtomLocation.center.ToString() && (o.Value == ButtomType.enable.ToString() || o.Value == ButtomType.disable.ToString())))
                            BuliderButtons(o.Operations, o.Code, o.AutoId, !o.Enable ? ButtomType.enable : ButtomType.disable);
                        if (Buttons.Any(o => o.Location == ButtomLocation.center.ToString() && o.Value == ButtomType.delete.ToString()))
                            BuliderButtons(o.Operations, o.Code, o.AutoId, ButtomType.delete);
                    }
                });
            }
            tableListModel.Body = Data;
            tableListModel.Total = Total;
            tableListModel.Header = Headers;
            if (Global.IsAdmin && (Buttons is null || !Buttons.Any()))
            {
                BuliderButtons(tableListModel.Operations, "", 0, ButtomType.add);
            }
            else
            {
                if (Buttons.Any(o => o.Value == ButtomType.add.ToString()))
                    BuliderButtons(tableListModel.Operations, "", 0, ButtomType.add);
            }
            return tableListModel.Succeed();
        }

        #region protected 

        protected override void BuliedTableResConfig(List<TableListHeaderModele> Headers, string pageType)
        {
            List<Dictionary<object, object>> rules = new List<Dictionary<object, object>>();
            Dictionary<object, object> rule = new Dictionary<object, object>();
            ///编码
            rule.Add("required", true);
            rule.Add("message", this.CommonText("fieldsrequired"));
            rule.Add("trigger", "blur");
            rules.Add(rule);
            rule = new Dictionary<object, object>();
            rule.Add("min", 1);
            rule.Add("max", 30);
            rule.Add("message", this.Resources("codemax"));
            rule.Add("trigger", "blur");
            rules.Add(rule);
            rule = new Dictionary<object, object>();
            rule.Add("pattern", "^([a-zA-Z0-9]){1,30}$");
            rule.Add("message", this.Resources("codedregx"));
            rule.Add("trigger", "blur");
            rules.Add(rule);
            Headers.Add(new TableListHeaderModele()
            {
                Key = "code",
                Name = this.CommonText("thcode"),
                Align = "left",
                Rules = pageType != "view" ? rules : new List<Dictionary<object, object>>(),
                Show = true,
                Editor = pageType != "view",
                ControlType = ControlType.text,
            });
            ///中文名
            var rules1 = new List<Dictionary<object, object>>();
            rule = new Dictionary<object, object>();
            rule.Add("required", true);
            rule.Add("message", this.CommonText("fieldsrequired"));
            rule.Add("trigger", "blur");
            rules1.Add(rule);
            ///长度
            rule = new Dictionary<object, object>();
            rule.Add("min", 1);
            rule.Add("max", 100);
            rule.Add("message", this.Resources("cnnamemax"));
            rule.Add("trigger", "blur");
            rules1.Add(rule);
            Headers.Add(new TableListHeaderModele()
            {
                Key = "cnName",
                Name = this.CommonText("thcnname"),
                Align = "center",
                Rules = pageType != "view" ? rules1 : new List<Dictionary<object, object>>(),
                Show = true,
                Editor = pageType != "view",
                ControlType = ControlType.textarea
            });
            ///英文名 
            var rules2 = new List<Dictionary<object, object>>();
            rule = new Dictionary<object, object>();
            rule.Add("required", true);
            rule.Add("message", this.CommonText("fieldsrequired"));
            rule.Add("trigger", "blur");
            rules2.Add(rule);
            ///长度
            rule = new Dictionary<object, object>();
            rule.Add("min", 1);
            rule.Add("max", 100);
            rule.Add("message", this.Resources("ennamemax"));
            rule.Add("trigger", "blur");
            rules2.Add(rule);
            Headers.Add(new TableListHeaderModele()
            {
                Key = "enName",
                Name = this.CommonText("thenname"),
                Align = "center",
                Rules = pageType != "view" ? rules2 : new List<Dictionary<object, object>>(),
                Show = true,
                Editor = pageType != "view",
                ControlType = ControlType.textarea
            });
            Headers.Add(new TableListHeaderModele()
            {
                Key = "enable",
                Name = CommonText("thstate"),
                Align = "center",
                Show = true,
                Editor = pageType != "view" && pageType != "add",
                Options = new List<Options>() { new Options { Label = CommonText("btnenable"), Value = true }, new Options { Label = CommonText("btndisable"), Value = false }, },
                ControlType = ControlType.radio
            });

        }

        public IResponseMessage Template(string key)
        {
            return new ParametersValue_IntPut() { CNName = "", Code = "", Enable = true, ENName = "", MainCode = "" }.Succeed();
        }

        /// <summary>
        /// 根据编码获取查用参数值
        /// </summary>
        /// <param name="mainCode"></param>
        /// <returns></returns>
        public IResponseMessage Tree(string mainCode)
        {
            List<ParameterTree> trees = business.ParameterTrees(MainCode: mainCode);
            List<GlobalTree> globalTrees = new List<GlobalTree>();
            if (trees.Any())
            {
                trees.GroupBy(o => new { o.ParameterId, o.ParameterName, o.ParameterCode, o.ParameterENName }).ToList().ForEach(g =>
                {
                    GlobalTree tree = new GlobalTree()
                    {
                        CNName = g.Key.ParameterName,
                        ENName = g.Key.ParameterENName,
                        Code = g.Key.ParameterCode,
                        Id = long.Parse(g.Key.ParameterId + "10001"),
                        Label = Global.IsChinese ? g.Key.ParameterName : g.Key.ParameterENName,
                        Disabled = true
                    };
                    g.Where(child => child.ParameterCode == g.Key.ParameterCode).ToList().ForEach(c =>
                    {
                        tree.Children.Add(new GlobalTree()
                        {
                            CNName = c.ValueName,
                            ENName = c.ValueENName,
                            Code = c.ValueCode,
                            Id = c.ValueId,
                            Label = !Global.IsChinese ? c.ValueENName : c.ValueName
                        });
                    });
                    globalTrees.Add(tree);
                });
            }
            return globalTrees.Succeed();
        }
        #endregion
    }
}
